package cn.six1943.deepchat.module.ai.service.model;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.six1943.deepchat.module.ai.api.IModelApi;
import cn.six1943.deepchat.module.ai.dal.dataobject.provider.ProviderDO;
import cn.six1943.deepchat.module.ai.dal.mysql.provider.ProviderMapper;
import cn.six1943.deepchat.module.ai.enums.ApiConstants;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.six1943.deepchat.module.ai.controller.admin.umodel.vo.*;
import cn.six1943.deepchat.module.ai.dal.dataobject.model.ProviderInstDO;
import cn.six1943.deepchat.module.ai.dal.dataobject.model.ModelDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.six1943.deepchat.module.ai.dal.mysql.model.ProviderInstMapper;
import cn.six1943.deepchat.module.ai.dal.mysql.model.ModelMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.six1943.deepchat.module.ai.enums.ErrorCodeConstants.*;

/**
 * 提供商 Service 实现类
 *
 * @author at1943
 */
@Service
@Validated
public class ProviderInstServiceImpl implements ProviderInstService {

    @Resource
    private ProviderInstMapper providerInstMapper;
    @Resource
    private ModelMapper modelMapper;
    @Resource
    private ProviderMapper providerMapper;
    @Resource
    private Map<String, IModelApi> modelApiMap;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProviderInst(AppProviderInstSaveReqVO saveReqVO) {
        ProviderDO providerDO = new ProviderDO();
        providerDO.setType(saveReqVO.getProviderType());
        providerDO.setName(saveReqVO.getName());
        providerDO.setAvatar(saveReqVO.getAvatar());
        providerDO.setCode(IdUtil.nanoId());
        providerMapper.insert(providerDO);

        ProviderInstDO providerInst = BeanUtils.toBean(saveReqVO, ProviderInstDO.class);
        providerInst.setProviderId(providerDO.getId());
        // 插入
        providerInstMapper.insert(providerInst);
        IModelApi service = modelApiMap.get(ApiConstants.getServiceName(providerInst.getProviderType()));

        List<ModelDO> models = service.getModels(providerInst);
        // 插入子表
        createModelList(providerInst.getId(), models);
        // 返回
        return providerInst.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProviderInst(Long id) {
        // 校验存在
        ProviderInstDO providerInstDO = validateProviderInstExists(id);
        if (providerInstDO.getDataType() == 1) {
            throw new ServiceException(400, "内置提供商不能删除");
        }
        // 删除子表
        deleteModelByKeyId(id);
        providerInstMapper.deleteById(id);
        providerMapper.deleteById(providerInstDO.getProviderId());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveProviderInst(AppProviderInstUpdateReqVO saveReqVO) {
        ProviderInstDO providerInst = BeanUtils.toBean(saveReqVO, ProviderInstDO.class);
        if (ObjectUtil.isEmpty(saveReqVO.getId())) {
            // 插入
            providerInstMapper.insert(providerInst);
            IModelApi service = modelApiMap.get(ApiConstants.getServiceName(providerInst.getProviderType()));

            List<ModelDO> models = service.getModels(providerInst);
            // 插入子表
            createModelList(providerInst.getId(), models);
        } else {
            // 校验存在
            validateProviderInstExists(saveReqVO.getId());
            providerInstMapper.updateById(providerInst);
        }
        // 返回
        return providerInst.getId();
    }

    @Override
    public void verifyProviderInst(AppProviderInstUpdateReqVO saveReqVO) {
        IModelApi service = modelApiMap.get(ApiConstants.getServiceName(saveReqVO.getProviderType()));

        ProviderInstDO providerInst = BeanUtils.toBean(saveReqVO, ProviderInstDO.class);
        List<ModelDO> models = service.getModels(providerInst);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProviderInst(AppProviderInstSaveReqVO updateReqVO) {
        // 校验存在
        validateProviderInstExists(updateReqVO.getId());
        // 更新
        ProviderInstDO updateObj = BeanUtils.toBean(updateReqVO, ProviderInstDO.class);
        providerInstMapper.updateById(updateObj);
    }

    @Override
    public void statusProviderInst(Long id, Integer status) {
        // 校验存在
        validateProviderInstExists(id);
        // 更新状态
        providerInstMapper.update(Wrappers.<ProviderInstDO>lambdaUpdate()
                .set(ProviderInstDO::getStatus, status)
                .eq(ProviderInstDO::getId, id));
    }

    private ProviderInstDO validateProviderInstExists(Long id) {
        ProviderInstDO providerInstDO = providerInstMapper.selectById(id);
        if (providerInstDO == null) {
            throw exception(PROVIDER_INST_NOT_EXISTS);
        }
        return providerInstDO;
    }

    @Override
    public ProviderInstDO getProviderInst(Long id) {
        return providerInstMapper.selectById(id);
    }

    @Override
    public ProviderInstDO getProviderInstByProviderId(Long providerId) {
        return providerInstMapper.selectOne(ProviderInstDO::getProviderId, providerId);
    }

    @Override
    public PageResult<ProviderInstDO> getProviderInstPage(AppProviderInstPageReqVO pageReqVO) {
        return providerInstMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ProviderInstDO> getProviderInstList(AppProviderInstPageReqVO pageReqVO) {
        return providerInstMapper.selectList(Wrappers.<ProviderInstDO>lambdaQuery());
    }

    // ==================== 子表（模型） ====================

    @Override
    public List<ModelDO> getModelListByKeyId(Long keyId) {
        return modelMapper.selectListByKeyId(keyId);
    }

    private void createModelList(Long keyId, List<ModelDO> list) {
        list.forEach(o -> {
            o.setKeyId(keyId);
            o.setName(o.getCode());
            o.setStatus(1);
        });
        Collections.sort(list, Comparator.comparing(ModelDO::getCode).reversed());
        modelMapper.insertBatch(list);
    }

    @Override
    public Long createModel(AppModelSaveReqVO createReqVO) {
        validateProviderInstExists(createReqVO.getKeyId());
        ModelDO obj = BeanUtils.toBean(createReqVO, ModelDO.class);
        modelMapper.insert(obj);
        return obj.getId();
    }

    @Override
    public Long updateModel(AppModelSaveReqVO createReqVO) {
        validateProviderInstExists(createReqVO.getKeyId());
        ModelDO obj = BeanUtils.toBean(createReqVO, ModelDO.class);
        modelMapper.updateById(obj);
        return obj.getId();
    }

    @Override
    public void deleteModel(Long id) {
        modelMapper.deleteById(id);
    }

    @Override
    public void statusInstModel(Long id, Integer status) {
        // 校验存在
        // validateProviderInstExists(id);
        // 更新状态
        modelMapper.update(Wrappers.<ModelDO>lambdaUpdate()
                .set(ModelDO::getStatus, status)
                .eq(ModelDO::getId, id));
    }

    @Override
    public List<ModelDO> getModelList() {
        return modelMapper.selectModelList();
    }

    private void updateModelList(Long keyId, List<ModelDO> list) {
        deleteModelByKeyId(keyId);
		list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createModelList(keyId, list);
    }

    private void deleteModelByKeyId(Long keyId) {
        modelMapper.deleteByKeyId(keyId);
    }

}